package com.dreamo.pache;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.format.Time;
import android.widget.TextView;

import com.dreamo.pache.data.ITicket;
import com.dreamo.pache.test.MockTicket;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.MarkerOptions;

public class TicketScreenActivity extends Activity implements
        ConnectionCallbacks, OnConnectionFailedListener, LocationListener {

    final static String SAVED_TICKET = "com.dreamo.pache.Saved_Ticket";
    // These settings are the same as the settings for the map. They will in
    // fact give you updates at
    // the maximal rates currently possible.
    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(10000) // 10 seconds
            .setFastestInterval(16) // 16ms = 60fps
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    private CountDownTimer timer;
    ITicket ticket;
    TextView timerText;

    private GoogleMap mMap;
    private LocationClient mLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView();
        setContentView(R.layout.activity_ticket_screen);
        timerText = (TextView) findViewById(R.id.ticket_timer);
        timerText.setText("");

        if (savedInstanceState == null) {
            ticket = new MockTicket();
        } else {
            byte[] ticketInBytes = savedInstanceState
                    .getByteArray(SAVED_TICKET);
            ticket = new MockTicket(ticketInBytes);
        }

        Time now = new Time();
        now.setToNow();
        Time expiry = ticket.getExpiryTime();
        long toExpiryInMillSeconds = expiry.toMillis(false)
                - now.toMillis(false);

        if (toExpiryInMillSeconds >= 0) {
            timer = new CountDownTimer(toExpiryInMillSeconds, 1000) {
                @Override
                public void onTick(long millis) {
                    long seconds = millis / 1000;
                    timerText.setText(String
                            .format("%02d:%02d:%02d", seconds / 3600,
                                    (seconds % 3600) / 60, seconds % 60));
                }

                @Override
                public void onFinish() {
                    timerText.setText("Ticket has expired");
                }

            };
            timer.start();
        }
        // TODO: handle error case
        else {

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mLocationClient != null) {
            mLocationClient.disconnect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        setupMap();
        setupLocationClient();
        mLocationClient.connect();
    }

    @Override
    protected void onStop() {
        // System.out.println();
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle saveInstanceState) {
        saveInstanceState.putByteArray(SAVED_TICKET, this.ticket.serialize());
        super.onSaveInstanceState(saveInstanceState);
    }

    private void setupLocationClient() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
                    this); // OnConnectionFailedListener
        }
    }

    private void setupMap() {
        // Do a null check to confirm that we have not already instantiated the
        // map.
        if (mMap == null) {
            // Try to obtain the map from the MapFragment.
            mMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.ticket_map)).getMap();
        }
        if (mMap != null) {
            mMap.setMyLocationEnabled(true);
            if (ticket != null) {
                mMap.addMarker(new MarkerOptions().position(ticket.Location)
                        .title("Car"));
            }
            // TODO: auto calculate zoom based on current location and car
            CameraUpdate cameraShowCar = CameraUpdateFactory.newLatLngZoom(
                    ticket.Location, 14);
            mMap.moveCamera(cameraShowCar);
        }
    }

    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle arg0) {
        mLocationClient.requestLocationUpdates(REQUEST, this); // LocationListener
    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub

    }

}
